package com.ibeeking.found.content.c.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.common.entity.KeyValue;
import com.ibeeking.found.common.entity.common.BroadcastSettingDTO;
import com.ibeeking.found.common.enums.PublishStatusEnum;
import com.ibeeking.found.common.utils.DataUtils;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.content.api.common.dto.MemberInfoDTO;
import com.ibeeking.found.content.api.feign.ContentMemberBClient;
import com.ibeeking.found.content.c.rest.service.IBroadcastCommentService;
import com.ibeeking.found.content.c.rest.service.IBroadcastService;
import com.ibeeking.found.content.service.common.dos.BroadcastCommentDO;
import com.ibeeking.found.content.service.common.param.BroadcastCommentParam;
import com.ibeeking.found.content.service.common.query.BroadcastCommentPageQuery;
import com.ibeeking.found.content.service.common.query.BroadcastQuery;
import com.ibeeking.found.content.service.common.vo.BroadcastCommentVO;
import com.ibeeking.found.content.service.common.vo.BroadcastVO;
import com.ibeeking.found.content.service.mapper.BroadcastCommentMapper;
import com.ibeeking.found.system.api.feign.SystemCommonFeignCClient;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName BroadcastCommentServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2022-02-21 16:01
 **/
@Service
public class BroadcastCommentServiceImpl extends ServiceImpl<BroadcastCommentMapper, BroadcastCommentDO> implements IBroadcastCommentService {

    @Resource
    private BroadcastCommentMapper broadcastCommentMapper;
    @Resource
    private IBroadcastService broadcastServiceImpl;
    @Resource
    private ContentMemberBClient contentMemberBClient;
    @Resource
    private SystemCommonFeignCClient systemCommonFeignCClient;

    @Override
    public Page<BroadcastCommentVO> pageList(BroadcastCommentPageQuery broadcastCommentPageQuery) {
        LambdaQueryWrapper<BroadcastCommentDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(broadcastCommentPageQuery.getRoomId() != null, BroadcastCommentDO::getRoomId, broadcastCommentPageQuery.getRoomId());
        wrapper.ge(StringUtils.isNotBlank(broadcastCommentPageQuery.getCreateTimeStart()), BroadcastCommentDO::getCreateTime, broadcastCommentPageQuery.getCreateTimeStart());
        wrapper.le(StringUtils.isNotBlank(broadcastCommentPageQuery.getCreateTimeEnd()), BroadcastCommentDO::getCreateTime, broadcastCommentPageQuery.getCreateTimeEnd());
        wrapper.orderByDesc(BroadcastCommentDO::getCreateTime);
        Page<BroadcastCommentDO> pages = broadcastCommentMapper.selectPage(new Page<BroadcastCommentDO>(broadcastCommentPageQuery.getPageNum(), broadcastCommentPageQuery.getPageSize()), wrapper);
        Page<BroadcastCommentVO> broadcastCommentVOPage = BeanUtil.convertPage(pages, BroadcastCommentVO.class);
        List<BroadcastCommentVO> records = broadcastCommentVOPage.getRecords();
        wrapperVO(records);
        return broadcastCommentVOPage;
    }

    @Override
    public BroadcastCommentVO view(Long id) {
        BroadcastCommentDO broadcastCommentDO = broadcastCommentMapper.selectById(id);
        BroadcastCommentVO broadcastCommentVO = JsonUtils.fromJson(broadcastCommentDO, BroadcastCommentVO.class);
        wrapperVO(Collections3.newArrayList(broadcastCommentVO));
        return broadcastCommentVO;
    }

    @Override
    public Boolean save(BroadcastCommentParam broadcastCommentParam) {
        Long userId = UserUtils.getUserId();
        if (broadcastCommentParam.getMemberId() == null) {
            broadcastCommentParam.setMemberId(userId);
        }
        DataUtils.falseThrowException(userId.equals(broadcastCommentParam.getMemberId()), "您只能修改您自己发表的评论!");
        ResponseResult<BroadcastSettingDTO> broadcastSettingDTOResult = systemCommonFeignCClient.broadcastSettingView();
        BroadcastSettingDTO broadcastSettingDTO = broadcastSettingDTOResult.getData();
        List<KeyValue> sensitiveWords = Optional.ofNullable(broadcastSettingDTO).map(BroadcastSettingDTO::getSensitiveWords).orElse(Collections3.emptyList());
        if (Collections3.isNotEmpty(sensitiveWords)) {
            List<String> sensitiveWordStrs = sensitiveWords.stream().map(x -> x.getValue().toString()).collect(Collectors.toList());
            for (String sensitiveWordStr : sensitiveWordStrs) {
                DataUtils.trueThrowException(broadcastCommentParam.getContent().contains(sensitiveWordStr), "您的评论内容包含敏感词: " + sensitiveWordStr);
            }
        }
        BroadcastCommentDO broadcastCommentDO = JsonUtils.fromJson(broadcastCommentParam, BroadcastCommentDO.class);
        if (broadcastCommentDO.getId() == null) {
            broadcastCommentDO.setPublishStatus(PublishStatusEnum.ENABLE.getValue());
            broadcastCommentMapper.insert(broadcastCommentDO);
        } else {
            broadcastCommentMapper.updateById(broadcastCommentDO);
        }
        return true;
    }


    public void wrapperVO(List<BroadcastCommentVO> vos) {
        if (Collections3.isEmpty(vos)) {
            return;
        }
        Set<Long> boradcastIds = vos.stream().map(BroadcastCommentVO::getId).collect(Collectors.toSet());
        Set<Long> memberIds = vos.stream().map(BroadcastCommentVO::getMemberId).collect(Collectors.toSet());
        List<BroadcastVO> broadcastVOList = broadcastServiceImpl.list(new BroadcastQuery().setIds(Collections3.newArrayList(boradcastIds)));
        Map<Long, String> broadcastMap = broadcastVOList.stream().collect(Collectors.toMap(BroadcastVO::getId, BroadcastVO::getRoomName));
        ResponseResult<List<MemberInfoDTO>> responseResult = contentMemberBClient.infoList(memberIds);
        List<MemberInfoDTO> memberInfoDTOList = Optional.ofNullable(responseResult.getData()).orElse(Collections3.emptyList());
        Map<Long, MemberInfoDTO> memberMap = memberInfoDTOList.stream().collect(Collectors.toMap(MemberInfoDTO::getId, x -> x));
        for (BroadcastCommentVO vo : vos) {
            vo.setRoomName(broadcastMap.get(vo.getId()));
            MemberInfoDTO memberInfoDTO = memberMap.get(vo.getMemberId());
            if (memberInfoDTO != null) {
                vo.setMemberName(memberInfoDTO.getName());
                vo.setMemberName(memberInfoDTO.getNickname());
            }
        }
    }
}
